package repository

import (
	"gitee.com/fx8s/goIrisTest/src/modules/story/model"
	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

//storyRepositoryMongo
type storyRepositoryMongo struct {
	db         *mgo.Database
	collection string
}

//NewstoryRepositoryMongo
func NewStoryRepositoryMongo(db *mgo.Database, collection string) *storyRepositoryMongo {
	return &storyRepositoryMongo{
		db:         db,
		collection: collection,
	}
}

// Save
func (r *storyRepositoryMongo) Save(entity *model.Story) error {
	err := r.db.C(r.collection).Insert(entity)
	return err
}

// FindById
func (r *storyRepositoryMongo) FindById(id string) (*model.Story, error) {
	var entity model.Story
	err := r.db.C(r.collection).Find(bson.M{"id": id}).One(&entity)

	if err != nil {
		return nil, err
	}

	return &entity, nil
}

// FindByProfileId
func (r *storyRepositoryMongo) FindByProfileId(profileId string) (model.Storys, error) {
	var entitys model.Storys
	err := r.db.C(r.collection).Find(bson.M{"profile.id": profileId}).All(&entitys)

	if err != nil {
		return nil, err
	} 

	return entitys, nil
}

// FindAll
func (r *storyRepositoryMongo) FindAll() (model.Storys, error) {
	var entitys model.Storys

	err := r.db.C(r.collection).Find(bson.M{}).All(&entitys)

	if err != nil {
		return nil, err
	}

	return entitys, nil
}
